package com.heihei.mymusic.util.dto;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

/**
 * DES加解密
 */
public class DESUtil {
	private String key;
	private final String DES_TYPE = "DESede/ECB/PKCS5Padding";

	private static DESUtil instance;

	private DESUtil() {
		initKey();
	}

	public static DESUtil getInstance() {
		if (instance == null) {
			instance = new DESUtil();
		}
		return instance;
	}

	public void initKey() {
		this.key = "#s^un2ye21fcn%|a0XpR,+vh";
	}

	/**
	 * 
	 * 方法描述 加密
	 *
	 * @param sourceText
	 * @return
	 * @throws Exception
	 * @author caichengzhe
	 * @throws
	 * @date 2018年5月30日下午5:07:29
	 */
	public String encryptText(String sourceText) {
		try {
			byte[] plaintext;
			plaintext = sourceText.getBytes("UTF-8");
			byte[] tdesKeyData = key.getBytes("ASCII");
			Cipher c3des = Cipher.getInstance(DES_TYPE);
			SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
			c3des.init(Cipher.ENCRYPT_MODE, myKey);
			byte[] cipherText = c3des.doFinal(plaintext);
			return DatatypeConverter.printBase64Binary(cipherText);
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 
	 * 对加密文字进行解密
	 *
	 * @param cipherText	加密过的文字
	 * @return
	 * @throws Exception
	 * 
	 * @author fengxiaolin
	 * @date 2016年4月13日 下午6:00:39
	 */
	public String decryptText(String cipherText) {
		try {
			byte[] encData = DatatypeConverter.parseBase64Binary(cipherText);
			Cipher decipher = Cipher.getInstance(DES_TYPE);
			byte[] tdesKeyData = key.getBytes("ASCII");
			SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
			decipher.init(Cipher.DECRYPT_MODE, myKey);
			byte[] plainText = decipher.doFinal(encData);
			return new String(plainText, "UTF-8");
		} catch (Exception e) {
			return "";
		}
	}

	// 测试
	@SuppressWarnings("deprecation")
	public static void main(String args[]) {
		String s = "ulQcjYJRp+s=";
		System.out.println(DESUtil.getInstance().decryptText(s));
	}
	

}
